package com.tpe.model.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.tpe.model.entity.Usuario;
import com.tpe.model.generic.dao.GenericCrudDao;
import com.tpe.model.repository.UsuarioRepository;

@Stateless
@Named(value="usuarioRepository")
public class UsuarioDao extends GenericCrudDao<Usuario> implements UsuarioRepository {

	public UsuarioDao(){
		super(Usuario.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Usuario> obterPorExemplo(Usuario user) {
		Map<String, Object> parametros = new HashMap<String, Object>();
		List<Usuario> lista = new ArrayList<Usuario>();

		try {

			StringBuffer sql = new StringBuffer(
					"SELECT u FROM Usuario u WHERE 1 = 1 ");

			if (user.getNome() != null && !user.getNome().isEmpty()) {
				sql.append("AND LOWER(u.nome) LIKE LOWER(:nome) ");
				parametros.put("nome", "%" + user.getNome() + "%");
			}
			
			if(user.getEmail() != null && !user.getEmail().isEmpty()){
				sql.append("AND LOWER(u.email) LIKE LOWER(:email) ");
				parametros.put("email", "%" + user.getEmail() + "%");
			}

			Query query = em.createQuery(sql.toString());

			for (Map.Entry<String, Object> o : parametros.entrySet())
				query.setParameter(o.getKey(), o.getValue());

			lista = query.getResultList();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return lista;
	}
	
	@Override
	public boolean verificaDuplicado(Usuario user) throws Exception {
		try {
			Query query = em.createQuery("SELECT COUNT(u) FROM Usuario u WHERE LOWER(u.email) = LOWER(:email)");
			query.setParameter("email", user.getEmail());
			Long i = (Long)query.getSingleResult();
			
			if(i.intValue() > 0)
				return true;
			else
				return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
	}
	
	@Override
	public Usuario obterPorEmail(Usuario usuario) throws Exception {
		try{
			Query query = em.createQuery("SELECT u FROM Usuario u WHERE LOWER(u.email) = LOWER(:email)");
			query.setParameter("email", usuario.getEmail());
			return (Usuario)query.getSingleResult();

		} catch(NoResultException e) {
			e.printStackTrace();
			throw new NoResultException();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Usuario> obterAtivos() throws Exception {
		Query query = em.createQuery("SELECT u FROM Usuario u WHERE u.flagConfirmado = true");
		return query.getResultList();
	}
}